package com.example.mybatis.dao.impl;


import com.example.mybatis.dao.IUserDAO;
import com.example.mybatis.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

public class UserDAOlmpl implements IUserDAO
{
    SqlSessionFactory sqlSessionFactory;

    public UserDAOlmpl(SqlSessionFactory sqlSessionFactory){
       this.sqlSessionFactory=sqlSessionFactory;
    }

    @Override
    public User queryUserById(int id) {
        // 4. 创建SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 5. 执行SqlSession对象执行查询，获取结果User
        // 第一个参数是User.xml的statement的id，第二个参数是执行sql需要的参数；
        User user = (User)sqlSession.selectOne("queryUserById", id);

        // 6. 打印结果
        System.out.println(user);

        // 7. 释放资源
        sqlSession.close();

        return user;
    }

    @Override
    public List<User> queryUserByUsername1(String name) {
        // 4. 创建SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 5. 执行SqlSession对象执行查询，获取结果User
        // 查询多条数据使用selectList方法
        List<User> users = sqlSession.selectList("queryUserByUsername", name);

        // 6. 打印结果
        for (Object u : users) {
            System.out.println(u);
        }

        // 7. 释放资源
        sqlSession.close();
        return users;
    }

    @Override
    public List<User> queryUserByUsername2(String name) {
        // 4. 创建SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        // 5. 执行SqlSession对象执行查询，获取结果User
        // 查询多条数据使用selectList方法
        List<User> users = sqlSession.selectList("queryUserByUsername2", name);

        // 6. 打印结果
        for (Object u : users) {
            System.out.println(u);
        }

        // 7. 释放资源
        sqlSession.close();
        return users;
    }

    @Override
    public int saveUser(User user) {

        SqlSession sqlSession = sqlSessionFactory.openSession();
        int result=sqlSession.insert("saveUser", user);
        System.out.println(user);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }

    @Override
    public int updateUserById(User user) {

        SqlSession sqlSession = sqlSessionFactory.openSession();
        int result=sqlSession.update("updateUserById", user);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }

    @Override
    public int deleteUserById(int id) {

        SqlSession sqlSession = sqlSessionFactory.openSession();
        int result=sqlSession.delete("deleteUserById", id);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }
}
